//
//  AdScrollView.m
//  Test
//
//  Created by lizq on 15/8/19.
//  Copyright (c) 2015年 lizq. All rights reserved.
//

#import "AdScrollView.h"

@interface AdScrollView ()
@property(nonatomic,strong)UIScrollView *adScroll;
@property(nonatomic,strong)UIView *currentView;
@property(nonatomic,assign)NSInteger index;
@property(nonatomic,strong)UISwipeGestureRecognizer *swip;
@end

@implementation AdScrollView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        self.adScroll = [[UIScrollView alloc] init];
        [self.adScroll setFrame:self.bounds];
        [self.adScroll setBackgroundColor:[UIColor whiteColor]];
        [self addSubview:self.adScroll];
        self.swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swip:)];
        self.swip.direction = UISwipeGestureRecognizerDirectionRight;
        [self addGestureRecognizer:self.swip];
        
        self.swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swip:)];
         self.swip.direction = UISwipeGestureRecognizerDirectionLeft;
        [self addGestureRecognizer:self.swip];
        self.index = 0;
    }
    return self;
}

- (void)reloadData {
    NSInteger total = [self.dataDelegate numberOfAdView];
    if(total < 1) return;
    self.currentView = [self.dataDelegate adViewWithIndex:self.index];
    [self.adScroll addSubview:self.currentView];
}

- (void)swip:(UISwipeGestureRecognizer *)swip {
    if(swip.direction == UISwipeGestureRecognizerDirectionRight) {
        if(self.index < [self.dataDelegate numberOfAdView] - 1) {
            self.index++;
        }else {
            self.index = 0;
        }
        [self.currentView removeFromSuperview];
        self.currentView = [self.dataDelegate adViewWithIndex:self.index];
        [self.adScroll addSubview:self.currentView];
    }
    
    if(swip.direction == UISwipeGestureRecognizerDirectionLeft) {
        if(self.index > 0) {
            self.index--;
        }else {
            self.index = [self.dataDelegate numberOfAdView] - 1;
        }
        [self.currentView removeFromSuperview];
        self.currentView = [self.dataDelegate adViewWithIndex:self.index];
        [self.adScroll addSubview:self.currentView];
    }
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
